package com.mojo.concurrent.concurrent_02_lock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock使用
 * <p>
 * 可重入的独占式锁，主要跟Synchronized对比
 * </p>
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class ReentrantLock01 {
    static ReentrantLock lock = new ReentrantLock();
    static volatile int n = 0;
    static AtomicInteger m = new AtomicInteger();
    static CountDownLatch latch = new CountDownLatch(10);

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {

                //lock.lock();
                for (int i1 = 0; i1 < 1000; i1++) {
                    n++;
                    m.incrementAndGet();
                }
                //lock.unlock();
                latch.countDown();
            }).start();
        }
        latch.await();
        //未加锁，n最终值小于10000
        System.out.println("n>>>>" + n);
        //原子类，m值结果正确
        System.out.println("m>>>>" + m.get());
    }

}

class MyRunnable implements Runnable {

    @Override
    public void run() {

    }
}
